package com.lytoyo.neihanduanzi.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lytoyo.neihanduanzi.model.dto.BlogInfoDto;
import com.lytoyo.neihanduanzi.model.dto.UserInfoDto;
import com.lytoyo.neihanduanzi.model.user.ChatMsg;
import com.lytoyo.neihanduanzi.model.user.UserInfo;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Package:com.lytoyo.neihanduanzi.utils
 *
 * @ClassName:WebsocketLocalContainerUtil
 * @Create:2025/3/4 11:16
 **/
@Component
@Slf4j
public class WebsocketLocalContainerUtil {
    //建立userId与userInfo基本信息对应的容器，通过userId可以获取用户基本信息
    private static Map<Long, UserInfo> userMap = new ConcurrentHashMap<>();

    //建立userId和ws Session的对应容器，通过userId获取Session会话信息
    private static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    private static Map<Long,UserInfo> attentionUserMap = new ConcurrentHashMap<>();

    private static Map<Long,Session> attentionSessionMap = new ConcurrentHashMap<>();


    public static Set<Long> getAllUserId(){
        return userMap.keySet();
    }

    public static Set<Long> getAllAttentionUserId() { return attentionUserMap.keySet();}

    //添加用户id与用户信息对应关系
    public static void addUser(Long userId, UserInfo userInfo) {
        if (userMap.get(userId) != null) {
            return;
        }
        WebsocketLocalContainerUtil.userMap.put(userId, userInfo);
    }

    public static void addAttentionUser(Long userId,UserInfo userInfo){
        if(attentionUserMap.get(userId) != null){
            return;
        }
        WebsocketLocalContainerUtil.attentionUserMap.put(userId,userInfo);
    }

    //获取用户的信息
    public static UserInfo getUser(Long userId) {
        return WebsocketLocalContainerUtil.userMap.get(userId);
    }

    public static UserInfo getAttentionUser(Long userId){
        return WebsocketLocalContainerUtil.attentionUserMap.get(userId);
    }

    //当用户断开ws连接时需要从容器中移除用户信息，避免内存溢出
    public static void removeUser(Long userId) {
        if(WebsocketLocalContainerUtil.userMap.get(userId) == null)  return;
        WebsocketLocalContainerUtil.userMap.remove(userId);
    }

    public static void removeAttentionUser(Long userId){
        if(WebsocketLocalContainerUtil.attentionUserMap.get(userId) == null) return;
        WebsocketLocalContainerUtil.attentionUserMap.remove(userId);
    }

    //添加用户id与session的对应关系
    public static void addSession(Long userId, Session session) {
        if(WebsocketLocalContainerUtil.sessionMap.get(userId) != null) return;
        WebsocketLocalContainerUtil.sessionMap.put(userId, session);
    }

    public static void addAttentionSession(Long userId, Session session){
        if(WebsocketLocalContainerUtil.attentionSessionMap.get(userId)!= null) return;
        WebsocketLocalContainerUtil.attentionSessionMap.put(userId,session);
    }

    //获取用户的session信息
    public static Session getSession(Long userId) {
        return WebsocketLocalContainerUtil.sessionMap.get(userId);
    }

    public static Session getAttentionSession(Long userId){
        return WebsocketLocalContainerUtil.attentionSessionMap.get(userId);
    }

    //当用户断开ws连接时候需要从容器中移除session，避免内存溢出
    public static void removeSession(Long userId) {
        if(WebsocketLocalContainerUtil.sessionMap.get(userId) == null) return;
        WebsocketLocalContainerUtil.sessionMap.remove(userId);
    }

    public static void removeAttentionSession(Long userId){
        if(WebsocketLocalContainerUtil.attentionSessionMap.get(userId) == null) return;
        WebsocketLocalContainerUtil.attentionSessionMap.remove(userId);
    }
    //构造消息体
    public static ChatMsg buildMsg(UserInfoDto userInfoDto, Integer msgType, Long otherUserId) {

        ChatMsg userChat = new ChatMsg()
                .setUserId(userInfoDto.getId())
                .setHeadPhoto(userInfoDto.getHeadPhoto())
                .setMsgType(msgType)
                .setNickname(userInfoDto.getNickname())
                .setOtherUserId(otherUserId);

        return userChat;
    }

    /**
     * 发送消息
     *
     * @param userId
     * @param chatMsg
     */
    public static void sendMsg(Long userId, ChatMsg chatMsg) {
        Session session = WebsocketLocalContainerUtil.getSession(userId);

        if (null != session) {
            session.getAsyncRemote().sendText(JSON.toJSONString(chatMsg, SerializerFeature.DisableCircularReferenceDetect));//异步发送消息
        }
    }

    public static void sendFollowMsg(Long userId, List blogInfoDtoList){
        Session session = WebsocketLocalContainerUtil.getAttentionSession(userId);
        log.info("blogInfoDtoList:{}",blogInfoDtoList);
        if(null != session){
            session.getAsyncRemote().sendText(JSON.toJSONString(blogInfoDtoList,SerializerFeature.DisableCircularReferenceDetect));
        }
    }

    public static boolean isUserOnline(Long receiverId) {
        Session session = WebsocketLocalContainerUtil.getSession(receiverId);
        return session != null ? true : false;
    }
}
